//用于localstorage的增加删除查询
import storage from 'good-storage'
const SEARCHKETY = "_SEARCH_ZCK_"
const SEARCH_MAX_LEN = 15;


const PLAYKEY = '_PLAY_ZCK_'
const PLAY_MAX_LEN = 200;

function insertArray(arr,val,compare,maxlen){
    let index = arr.findIndex(compare);
    if(index === 0){
        return
    }
    if(index > 0){
        arr.splice(index,1)
    }
    arr.unshift(val);
    if(maxlen && arr.length > maxlen){
        arr.pop()
    }
}
function deleteFromArray(arr,compare){
    let index = arr.findIndex(compare);
    if(index>-1){
        arr.splice(index,1);
    }
}
export function saveSearch(querry){
    let searches = storage.get(SEARCHKETY,[]);
    insertArray(searches,querry,(item)=>{
        return item === querry
    },SEARCH_MAX_LEN)
    storage.set(SEARCHKETY,searches);
    return searches
}
export function deleteSearch(querry){
    let searches = storage.get(SEARCHKETY,[]);
    deleteFromArray(searches,(item)=>{
        return item === querry
    })
    storage.set(SEARCHKETY,searches);
    return searches
}
export function clearSearch(){
    storage.remove(SEARCHKETY);
    return []
}
export function loadSearch(){
    let searches = storage.get(SEARCHKETY,[]);
    return searches;
}




export function savePlay(song){//歌曲插入历史列表
    let songs = storage.get(PLAYKEY,[]);
    insertArray(songs,song,(item)=>{
        return item.id === song.id
    },PLAY_MAX_LEN)
    storage.set(PLAYKEY,songs);
    return songs
}

export function loadPlay(){
    let songs = storage.get(PLAYKEY,[]);
    return songs;
}
export function deletePlay(song){
    let songs = storage.get(PLAYKEY,[]);
    deleteFromArray(songs,(item)=>{
        return item.id === song.id
    })
    storage.set(PLAYKEY,songs);
    return songs
}
export function clearPlay(){
    storage.remove(PLAYKEY);
    return []
}

